<template>
  <NavBar></NavBar>
  <div class="sickness-container">
    <div class="sickness-box">
      <div class="search-title">生病记录查询</div>
      <el-form :model="form" @submit.prevent="handleSearch">
        <el-form-item>
          <el-input
              v-model="form.searchParam"
              placeholder="输入牛耳标或牛ID进行筛选..."
              style="max-width: 600px"
              class="input-with-select"
          >
            <template #append>
              <el-button type="primary" :icon="Search" native-type="submit" />
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <div class="filter-sort-container">
        <el-select v-model="sortField" placeholder="排序字段" @change="handleSort">
          <el-option label="默认排序" value="" />
          <el-option label="按牛编号排序" value="cattleId" />
          <el-option label="按疾病名称排序" value="diseaseName" />
          <el-option label="按发病日期排序" value="startDate" />
          <el-option label="按治疗花费排序" value="cost" />
        </el-select>
        <el-select v-model="sortOrder" placeholder="排序方式" @change="handleSort">
          <el-option label="升序" value="asc" />
          <el-option label="降序" value="desc" />
        </el-select>
        <el-select v-model="diseaseFilter" placeholder="疾病类型筛选" @change="handleFilter">
          <el-option label="全部" value="" />
          <el-option 
            v-for="disease in diseaseTypes" 
            :key="disease" 
            :label="disease" 
            :value="disease" 
          />
        </el-select>
      </div>

      <div v-loading="loading" class="table-container">
        <el-table
            :data="sicknessData"
            style="width: 100%; height: 60vh;"
            empty-text="暂无生病记录"
        >
          <el-table-column prop="cattleId" label="牛编号" width="120" />
          <el-table-column prop="diseaseName" label="疾病名称" width="180" />
          <el-table-column prop="startDate" label="发病日期" width="180">
            <template #default="{row}">
              {{ new Date(row.startDate).toLocaleDateString() }}
            </template>
          </el-table-column>
          <el-table-column prop="endDate" label="康复日期" width="180">
            <template #default="{row}">
              {{ row.endDate ? new Date(row.endDate).toLocaleDateString() : '治疗中' }}
            </template>
          </el-table-column>
          <el-table-column prop="cost" label="治疗花费" width="120">
            <template #default="{row}">
              {{ row.cost ? `¥${row.cost.toFixed(2)}` : '¥0.00' }}
            </template>
          </el-table-column>
          <el-table-column prop="medicationUsed" label="使用药物" />
          <el-table-column prop="treatmentLocation" label="治疗地点" />
          <el-table-column prop="symptoms" label="症状描述">
            <template #default="{row}">
              <el-tooltip effect="dark" :content="row.symptoms" placement="top">
                <span class="symptoms-text">{{ row.symptoms?.slice(0, 15) }}...</span>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 已移除分页组件 -->
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { useStore } from "vuex";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import NavBar from "@/components/NavBar.vue";
import { Search } from "@element-plus/icons-vue";

export default {
  components: { NavBar },
  setup() {
    const store = useStore();
    const route = useRoute();
    const form = reactive({ searchParam: "" });
    const sicknessData = ref([]);
    const allSicknessData = ref([]); // 存储所有数据，用于筛选和排序
    const currentCattle = ref(null);
    const loading = ref(false);
    const sortField = ref("");
    const sortOrder = ref("asc");
    const diseaseFilter = ref("");
    const diseaseTypes = ref([]);

    // 移除分页相关状态
    // const pageSize = 10000;
    // const total = ref(0);

    // 获取所有生病记录
    const fetchAllSicknessHistory = async () => {
      loading.value = true;
      try {
        const resp = await store.dispatch("fetchAllSicknessHistory", {
          token: store.state.user.token
        });

        if (resp.status === "success") {
          sicknessData.value = resp.data;
          allSicknessData.value = resp.data;
          
          // 提取所有疾病类型用于筛选
          const diseases = new Set();
          allSicknessData.value.forEach(item => {
            if (item.diseaseName) {
              diseases.add(item.diseaseName);
            }
          });
          diseaseTypes.value = Array.from(diseases);
        }
      } catch (error) {
        ElMessage.error("获取生病记录失败");
      } finally {
        loading.value = false;
      }
    };

    // 获取特定牛的生病记录
    const fetchSicknessHistory = async (cattleId) => {
      loading.value = true;
      try {
        const resp = await store.dispatch("fetchSicknessHistory", {
          cattleId,
          token: store.state.user.token
        });

        if (resp.status === "success") {
          sicknessData.value = resp.data;
          allSicknessData.value = resp.data;
          currentCattle.value = store.getters.getCattleById(cattleId);
        }
      } catch (error) {
        ElMessage.error("获取生病记录失败");
      } finally {
        loading.value = false;
      }
    };

    // 排序处理
    const handleSort = () => {
      if (!sortField.value) {
        // 如果没有选择排序字段，恢复原始数据顺序
        applyFilters();
        return;
      }
      
      const sortedData = [...sicknessData.value].sort((a, b) => {
        let valueA = a[sortField.value];
        let valueB = b[sortField.value];
        
        // 日期类型特殊处理
        if (sortField.value === 'startDate' || sortField.value === 'endDate') {
          valueA = new Date(valueA || 0).getTime();
          valueB = new Date(valueB || 0).getTime();
        }
        
        // 数字类型特殊处理
        if (sortField.value === 'cost') {
          valueA = parseFloat(valueA || 0);
          valueB = parseFloat(valueB || 0);
        }
        
        if (sortOrder.value === 'asc') {
          return valueA > valueB ? 1 : -1;
        } else {
          return valueA < valueB ? 1 : -1;
        }
      });
      
      sicknessData.value = sortedData;
    };

    // 筛选处理
    const handleFilter = () => {
      applyFilters();
    };
    
    // 应用筛选条件
    const applyFilters = () => {
      let filteredData = [...allSicknessData.value];
      
      // 应用疾病类型筛选
      if (diseaseFilter.value) {
        filteredData = filteredData.filter(item => 
          item.diseaseName === diseaseFilter.value
        );
      }
      
      // 应用搜索参数筛选
      if (form.searchParam) {
        filteredData = filteredData.filter(item => 
          item.cattleId === form.searchParam || 
          item.earTag === form.searchParam
        );
      }
      
      sicknessData.value = filteredData;
      
      // 重新应用排序
      if (sortField.value) {
        handleSort();
      }
    };

    // 搜索处理
    const handleSearch = async () => {
      if (!form.searchParam) {
        // 如果搜索框为空，显示所有记录
        fetchAllSicknessHistory();
        return;
      }
      
      loading.value = true;
      const isEarTag = /^[a-zA-Z]/.test(form.searchParam);
      const isID = /^\d+$/.test(form.searchParam);

      try {
        if (isID) {
          await fetchSicknessHistory(form.searchParam);
        } else if (isEarTag) {
          const cattle = await store.dispatch("fetchCattleByEarTag", {
            earTag: form.searchParam,
            token: store.state.user.token
          });
          if (cattle) await fetchSicknessHistory(cattle.id);
        } else {
          ElMessage.error("输入的ID格式或耳标格式不正确");
        }
      } catch (error) {
        ElMessage.error("未找到相关牛只");
      } finally {
        loading.value = false;
      }
    };

    // 初始化
    onMounted(() => {
      const cattleId = route.query.cattleId;
      if (cattleId) {
        fetchSicknessHistory(cattleId);
        form.searchParam = cattleId;
      } else {
        // 默认加载所有生病记录
        fetchAllSicknessHistory();
      }
    });

    return {
      form,
      sicknessData,
      currentCattle,
      loading,
      handleSearch,
      Search,
      sortField,
      sortOrder,
      diseaseFilter,
      diseaseTypes,
      handleSort,
      handleFilter
    };
  }
};
</script>

<style scoped>
.sickness-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.sickness-box {
  width: 80%;
  background-color: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.search-title {
  text-align: center;
  font-size: 24px;
  margin-bottom: 20px;
  color: #409eff;
  font-weight: 600;
}

.filter-sort-container {
  display: flex;
  gap: 10px;
  margin: 15px 0;
}

.cattle-info {
  margin: 20px 0;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.table-container {
  margin-top: 20px;
}

.symptoms-text {
  cursor: help;
  border-bottom: 1px dashed #999;
}

/* 移除分页相关样式 */
.pagination-container {
  display: none;
}

.page-item {
  cursor: pointer;
  user-select: none;
  list-style: none;
  margin: 0 2px;
}

.page-item.disabled .page-link {
  pointer-events: none;
  opacity: 0.6;
}

.page-item.active .page-link {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

.page-link {
  display: block;
  padding: 8px 16px;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  color: #409eff;
  text-decoration: none;
  transition: all 0.2s;
}

.page-link:hover {
  background-color: #f8f9fa;
}

@media (max-width: 768px) {
  .sickness-box {
    width: 95%;
    padding: 20px;
  }

  .el-table {
    font-size: 14px;
  }
  
  .filter-sort-container {
    flex-direction: column;
  }
}
</style>